package org.avenger.bucky.manager;

import com.mongodb.Block;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.avenger.bucky.model.TestQuestion;
import org.bson.Document;
import org.bson.types.ObjectId;

/**
 * 查找相似的TestQuestion对象，只有题干和选项都相似时，才返回
 */
public class FindSimilarTestQuestionByRegexBlock implements Block<Document> {

    private Pattern subjectPattern;
    private List<Pattern> optionPatternList;
    private MongoManager mongoManager;
    private List<TestQuestion> testQuestionList;

    public FindSimilarTestQuestionByRegexBlock() {
    }

    public FindSimilarTestQuestionByRegexBlock(Pattern subjectPattern,
        List<Pattern> optionPatternList, MongoManager mongoManager, List<TestQuestion> testQuestionList) {
        this.subjectPattern = subjectPattern;
        this.optionPatternList = optionPatternList;
        this.mongoManager = mongoManager;
        this.testQuestionList = testQuestionList;
    }

    @Override
    public void apply(Document existDocument) {
        boolean subjectSimilar = false;
        boolean optionSimilar = false;

        // 判断题干是否匹配
        String existSubject = existDocument.getString("subject");
        Matcher subjectMatcher = subjectPattern.matcher(existSubject);
        if (subjectMatcher.find()){
            subjectSimilar = true;
        }

        // 判断选项是否匹配
        List<Document> existDocumentList = (List<Document>) existDocument.get("option_list");
        if (null != existDocumentList && existDocumentList.size()>0){
            for (int x=0; x<optionPatternList.size(); x++){
                for (int y=0; y<existDocumentList.size(); y++){
                    if (optionPatternList.get(x).matcher(existDocumentList.get(y).getString("content")).find()){
                        optionSimilar = true;
                    }
                }
            }
        }

        // 只有题干和选项都匹配才行，然后保存到testQuestionList列表中
        if (subjectSimilar && optionSimilar){
            // 查找匹配的TestQuestion对象
            TestQuestion testQuestion = mongoManager.findByObjectId((ObjectId) existDocument.get("_id"));
            testQuestionList.add(testQuestion);
            return;
        }
    }
}
